import 'package:flutter/cupertino.dart';
import 'package:scrollview_observer/scrollview_observer.dart';
import '../../../../lib_basemodel/user/user.dart';
import '../../../../lib_baseview/widget/dialogs.dart';
import '../../../../lib_runtime/logger.dart';
import '../../../../resource/language/generated/l10n.dart';
import '../../msg/room_msg.dart';

///
/// 底部弹幕列表的数据模型
///
class BarrageListModel extends ChangeNotifier {
  ScrollController scrollController = ScrollController();
  ListObserverController? _observerController;
  // final ItemScrollController itemScrollController = ItemScrollController();
  // final ItemPositionsListener itemPositionsListener = ItemPositionsListener.create();
  // final ScrollOffsetController scrollOffsetController = ScrollOffsetController();

  String? channel;
  String securityNotice = T.current.room_security_notice;

  double preHeight = 0;

  ListObserverController get observerController => _observerController ??=
      ListObserverController(controller: scrollController)
        ..initialIndex = msgList.length - 1;

  /// 公屏消息list
  List<RoomMsg> _msgList = [];
  List<RoomMsg> get msgList => _msgList;
  set msgList(List<RoomMsg> list) {
    _msgList = [
      ...list,
      ...localMsgList,
    ];
    notifyListeners();

    // jumpBottom();
  }

  /// 是否开启公屏
  bool _enable = false;
  bool get enable => _enable;
  set enable(bool value) {
    if (_enable == value) return;
    _enable = value;

    if (!_enable) {
      _msgList.clear();
    }
    notifyListeners();
  }

  void jumpBottom() {
    observerController.animateTo(
        index: msgList.length - 1,
        duration: const Duration(milliseconds: 250),
        curve: Curves.easeInOut);
  }

  Function(BuildContext context, User user)? callBack;
  BarrageListModel(this.callBack);

  getRoomRecordData() {}

  int channelId = 0; //服务器的房间id
  setChannelId(int? chanId) {
    channelId = chanId ?? 0;
  }

  getSimpleUserShow(int uid, int channelId, BuildContext context) async {
    try {
      showLoadingDialog();
      // var result =
      //     await AutoRideApi.instance.getSimpleChanneUser(uid, channelId);
      // dismissLoadingDialog();
      // if (!result.isSuccess || result.data == null) {
      //   return;
      // }
      // final user = result.data as SimpleChannelUser;
      // if (context.mounted)
      //   await RoomPersonalDataWidget.show(context, channel, user);

      dismissLoadingDialog();
    } catch (e, r) {
      RLog.d('Show user info with error: $e, stack: $r');
    }
  }

  void addMsg(RoomMsg msg) {
    /// insert 0，会导致list中所有index变化
    // msgList.insert(0, msg);
    msgList.add(msg);
    if (msgList.length > 500) {
      msgList = msgList.sublist(msgList.length - 500, msgList.length);
    }
    notifyListeners();

    jumpBottom();
    // _newMsgHandle();
  }

  /// 客户端本地加到公屏的消息
  List<RoomMsg> get localMsgList => [
        // if (securityNotice.isNotEmpty) securityMsg,
        // if (channel?.notice.isNotEmpty ?? false) noticeMsg
      ];

  /// 安全提示
  // RoomMsg get securityMsg =>
  //     _createLocalMsg(securityNotice ?? '', '0xFF29EEAA');

  /// 公告
  // RoomMsg<ChatContent> get noticeMsg =>
  //     _createLocalMsg(channel?.notice ?? '', '0xFFF0DE9E');

  // RoomMsg _createLocalMsg(String msgStr, String colorStr) {
  //   ChatContent chatContent = ChatContent();
  //   chatContent.showItem?.clear();
  //   chatContent.showItem?.add(ShowItem(
  //       style: ItemStyle.text, text: msgStr, size: 11, color: colorStr));
  //   MessageData msgData = MessageData()
  //     // ..scene = Scene.ROOM_TEXT_CHAT
  //     ..content = msgStr;
  //   // ..content = Any.pack(chatContent);

  //   var msg = Message()
  //     ..type = MessageTypeEnum.chat
  //     ..time = DateTime.now().millisecondsSinceEpoch
  //     ..data = msgData;

  //   // return RoomMsg(msg, ChatContent());
  //   return RoomMsg(msg, msgStr);
  // }

  void scrollTo(RoomMsg? roomMsg) {
    if (roomMsg == null || msgList.isEmpty) return;
    // int index =
    //     msgList.indexWhere((element) => element.msg.id == roomMsg.msg.id);
    int index = 1;
    if (index >= 0) {
      observerController.animateTo(
          index: index,
          duration: const Duration(milliseconds: 250),
          curve: Curves.easeInOut,
          offset: (of) {
            return 50;
          });
    }
  }

  bool _newMsgHandling = false;
  ValueNotifier<int> _unReadMsgNum = ValueNotifier(0);
  void _newMsgHandle() async {
    if (_newMsgHandling) return;
    _newMsgHandling = true;
    ListViewOnceObserveNotificationResult result = await observerController
        .dispatchOnceObserve(isForce: true, isDependObserveCallback: false);
    if (result.observeResult?.displayingChildIndexList != null) {
      bool isBottom = result.observeResult?.displayingChildIndexList
              .any((element) => element >= msgList.length - 2) ??
          false;
      if (isBottom) {
        observerController.animateTo(
            index: msgList.length - 1,
            duration: const Duration(milliseconds: 250),
            curve: Curves.easeInOut);
      } else {
        int num = _unReadMsgNum.value + 1;
        _unReadMsgNum.value = num;
      }
    }
    _newMsgHandling = false;
  }

  ValueNotifier<int> get unReadMsgNum => _unReadMsgNum;

  void onObserve(ListViewObserveModel model) {
    bool isBottom = model.displayingChildIndexList
        .any((element) => element >= msgList.length - 2);
    if (isBottom) {
      _unReadMsgNum.value = 0;
    }
  }
}
